package org.biogroovy.io.local

import groovy.util.logging.Slf4j

import javax.xml.parsers.DocumentBuilderFactory

import org.biogroovy.io.AbsReader;
import org.biogroovy.io.IFetcher;
import org.biogroovy.models.Journal
import org.w3c.dom.Element
import org.w3c.dom.Node

/**
 * This class is responsible for reading the journal metadata as written out by the JournalWriter.
 *
 */
@Slf4j
class JournalReader extends AbsReader<Journal, Node> {

	@Override
	public void parse(Journal journal, Node el) {
		Element node = (Element)el;
		
		journal.title = node.getAttribute('title');
		journal.volume = node.getAttribute('volume');
		journal.publicationDate = dateFormatter.parse(node.getAttribute('pub-date'));
		journal.startPage =  Integer.parseInt(node.getAttribute('start-page'));
		journal.endPage = Integer.parseInt(node.getAttribute('end-page'));
		journal.issn = node.getAttribute('issn');
		journal.issue = node.getAttribute('issue');
		journal.rssUrl = node.getAttribute('rss-url');
		journal.imageUrl = node.getAttribute('image-url');
		journal.siteUrl = node.getAttribute('site-url');
		
	}

	@Override
	public Journal read(InputStream inputStream) throws IOException {
		def factory = DocumentBuilderFactory.newInstance();

		factory.setNamespaceAware(false);
		factory.setValidating(false);
		factory.setFeature("http://xml.org/sax/features/namespaces", false);
		factory.setFeature("http://xml.org/sax/features/validation", false);
		factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
		factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
		factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false)

		def builder  = factory.newDocumentBuilder();
		def root     = builder.parse(inputStream).documentElement

		log.debug( "xml: " + root);
		Journal journal = new Journal();
		parse(journal, root);
		return journal
	}



	@Override
	public Journal fetch(String id) throws IOException {
		//no-op
		return null;
	}

	@Override
	public URL getUrl(String id, Map<String, String> paramMap) {
		// no-op
		return null;
	}

	@Override
	public List<Journal> fetchAll(String id) throws IOException {
		// no-op
		return null;
	}

	@Override
	public List<Journal> readList(InputStream inputStream) throws IOException {
		// no-op
		return null;
	}

	@Override
	public IFetcher<Journal> getNewInstance() {
		return new JournalReader();
	}
}
